package cn.com.dcsgo;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * OrderApplication
 *
 * @author Dcsgo
 * @since 2025/3/11 9:03
 */
@EnableFeignClients//开启声明式远程调用
@EnableDiscoveryClient//开启服务发现
@SpringBootApplication
@MapperScan({"cn.com.dcsgo.mapper"})
public class OrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }

    /**
     * 一次性任务，在服务启动后会执行这个Bean的run方法
     * 它是个函数式接口
     *
     * @return ApplicationRunner
     */
    @Bean
    ApplicationRunner applicationRunner(NacosConfigManager nacosConfigManager) {
        return args -> {
            ConfigService configService = nacosConfigManager.getConfigService();
            /*
              dataId – 配置的 dataId
              group – 配置所在的组
              listener – 监听线程
             */
            configService.addListener("service-order.yaml", "DEFAULT_GROUP",
                    new Listener() {
                        /**
                         * 执行者，这里使用线程池
                         * @return Executor
                         */
                        @Override
                        public Executor getExecutor() {
                            return Executors.newFixedThreadPool(4);
                        }

                        /**
                         * 获取配置信息
                         * 监听的配置中的所有配置
                         * 不仅仅是发生了变化的
                         * @param configInfo configInfo
                         */
                        @Override
                        public void receiveConfigInfo(String configInfo) {
                            System.out.println("获取到的配置信息: " + configInfo);
                            //做些什么...
                            System.out.println("发送配置更新的邮件通知");
                        }
                    }
            );
            System.out.println("applicationRunner end");
        };
    }
}
